# -*- coding: utf-8 -*-

import logging
import traceback

from django.db.models import ProtectedError
from django.db.utils import DatabaseError
from core.response import JsonResponse
from rest_framework import exceptions
from rest_framework.exceptions import APIException as DRFAPIException, AuthenticationFailed
from rest_framework_simplejwt.exceptions import InvalidToken
from rest_framework.views import set_rollback

logger = logging.getLogger(__name__)


def CustomExceptionHandler(ex, context):
    """
    统一异常拦截处理
    目的:(1)取消所有的500异常响应,统一响应为标准错误返回
        (2)准确显示错误信息
    :param ex:
    :param context:
    :return:
    """
    msg = ''
    code = 500

    if isinstance(ex, InvalidToken):
        msg = ex.detail
        code = ex.status_code
    if isinstance(ex, AuthenticationFailed):
        msg = ex.detail
    elif isinstance(ex, DRFAPIException):
        set_rollback()
        msg = ex.detail
    elif isinstance(ex, exceptions.APIException):
        set_rollback()
        msg = ex.detail
    elif isinstance(ex, ProtectedError):
        set_rollback()
        msg = "删除失败:该条数据与其他数据有相关绑定"
    elif isinstance(ex, DatabaseError):
        logger.error(traceback.format_exc())
        set_rollback()
        msg = str(ex)
    elif isinstance(ex, Exception):
        logger.error(traceback.format_exc())
        msg = str(ex)

    # errorMsg = msg
    # for key in errorMsg:
    #     msg = errorMsg[key][0]

    return JsonResponse(msg=msg, code=code)
